package com.atguigu.dga.common;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ThreadDemo {

   static ThreadPoolExecutor poolExecutor=  new ThreadPoolExecutor(10,20,1L, TimeUnit.MINUTES,new LinkedBlockingDeque<>(2000));


    // 1-6 数组   1 每个值都做平方处理 2  以后 加总
    public static void main(String[] args) throws InterruptedException {


        Integer[] nums={1,2,3,4,5,6};
        long start = System.currentTimeMillis();

        List<Integer>  numsRsList=new ArrayList<>();
        List<CompletableFuture<Integer>>  futureList =new ArrayList<>();
        for (Integer num : nums) {

//            Thread.sleep(1000);
//            Integer numRs=   num*num;  //现货
            //numRs 现货

            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Integer numRs = num * num;
                return numRs;
            },poolExecutor);
          //  completableFuture 期货

           // numsRsList.add(numRs);
            futureList.add(completableFuture);
        }

        //期货转现货 交割
        numsRsList= futureList.stream().map(future -> future.join()).collect(Collectors.toList());
        System.out.println("duration = " +(  System.currentTimeMillis()- start));
        //2
         Integer sum=0;
        for (Integer numRs : numsRsList) {
            sum+=numRs;
        }
        System.out.println("sum = " + sum);

    }
}
